package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.LoginDto;
import com.heima.model.user.entity.User;
import com.heima.user.mapper.UserMapper;
import com.heima.user.service.UserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author dongcy
 * @date 2024/11/6 11:28
 * @description UserServiceImp
 */
@Service
@Slf4j
@Transactional
public class UserServiceImp extends ServiceImpl<UserMapper, User> implements UserService {


    @Override
    public ResponseResult login(LoginDto dto) {
        //点登录
        if (StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())) {

            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone, dto.getPhone());
            User one = baseMapper.selectOne(wrapper);
            if (one == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "手机号不存在");
            }
            //校验密码
            String salt = one.getSalt();
            String password = dto.getPassword();
            String pwd = DigestUtils.md5DigestAsHex((salt + password).getBytes());
            if (!pwd.equals(one.getPassword())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //校验正确  返回前端数据
            String token = AppJwtUtil.getToken(one.getId().longValue());
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            one.setSalt("");
            one.setPassword("");
            map.put("user", one);

            return ResponseResult.okResult(map);
        } else {
            Map<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }
    }
}
